package cc.sunni.api.interceptors;

import cc.sunni.common.Constant;
import cc.sunni.common.enums.UserStatus;
import cc.sunni.common.exception.RRException;
import cc.sunni.common.utils.JsonUtils;
import cc.sunni.common.utils.ResultEnum;
import cc.sunni.pojo.user.AppUser;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户激活状态检查拦截器
 * 发文章，修改文章，删除文章，
 * 发表评论，查看评论等等
 * 这些接口都是需要在用户激活以后，才能进行
 * 否则需要提示用户前往[账号设置]去修改信息
 */
public class UserActiveInterceptor extends BaseInterceptor implements HandlerInterceptor {

    /**
     * 拦截请求，访问controller之前
     *
     * @param request
     * @param response
     * @param handler
     * @return
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        String userId = request.getHeader("headerUserId");
        String userJson = redis.get(Constant.REDIS_USER_INFO + ":" + userId);
        AppUser user;
        if (StrUtil.isNotBlank(userJson)) {
            user = JSONUtil.toBean(userJson, AppUser.class);
        } else {
            throw new RRException(ResultEnum.UN_LOGIN);
        }

        if (user.getActiveStatus() == null || !user.getActiveStatus().equals(UserStatus.ACTIVE.type)) {
            throw new RRException(ResultEnum.USER_INACTIVE_ERROR);
        }

        /**
         * false：请求被拦截
         * true：请求通过验证，放行
         */
        return true;
    }


    /**
     * 请求访问到controller之后，渲染视图之前
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    /**
     * 请求访问到controller之后，渲染视图之后
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
